<template>
	<el-dialog :close-on-click-modal="false" :title="`${mode === 'add' ? '新增' : mode === 'edit' ? '修改' : '查看'}特殊作业记录`" width="700px" v-model="visible"
		@confirm="confirm" @cancel="visible = false" @close="closeDialog">
		<div class="formData">
			<el-form :model="formData" ref="ruleForm" label-width="120px" :rules="rules">
				<el-row>
					<el-col :span="12">
						<el-form-item label="拖轮" prop="tugId">
							<Select placeholder="请选择拖轮" :selectData="selects.tugList" v-model:value="formData.tugId"
								:disabled="mode == 'view'" v-model:label="formData.tugNo" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="作业项目" prop="workItemId">
							<Select placeholder="请选择项目" :selectData="selects.workItemList" v-model:value="formData.workItemId"
								:disabled="mode == 'view'" v-model:label="formData.workItemName" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="开始作业时间" prop="beginTime">
							<el-date-picker v-model="formData.beginTime" value-format="YYYY-MM-DD HH:mm:ss"
								type="datetime" :disabled="mode == 'view'" placeholder="请选择开始作业时间" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="结束作业时间" prop="endTime">
							<el-date-picker v-model="formData.endTime" value-format="YYYY-MM-DD HH:mm:ss"
								type="datetime" :disabled="mode == 'view'" placeholder="请选择结束作业时间" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="客户名称" prop="customerId">
							<RemoteSelect type="CUSTOMER_INFO" v-model:value="formData.customerId"
							placeholder="请输入客户名称"
								:disabled="mode == 'view'" v-model:label="formData.customerName" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="作业港区" prop="portAreaCode">
							<Select placeholder="请选择作业港区" disabled :dataConfig="{ params: { type: 'DICT',dictType:'PORT_AREA' } }"
								:disabled="mode == 'view'" v-model:value="formData.portAreaCode"
								v-model:label="formData.portAreaName" />
						</el-form-item>
					</el-col>
				</el-row>
				<!-- <el-row>
					<el-col :span="12">
						<el-form-item label="油耗" prop="oilConsume">
						  <el-input v-model="formData.oilConsume" placeholder="请输入油耗(L)" :disabled="mode == 'view'"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="行驶里程" prop="distance">
						  <el-input v-model="formData.distance" placeholder="请输入行驶里程" :disabled="mode == 'view'"></el-input>
						</el-form-item>
					</el-col>
				</el-row> -->
				<el-row>
					<el-col :span="12">
						<el-form-item label="作业地点" prop="workLocation">
							<el-input v-model="formData.workLocation" placeholder="请填写作业地点"
								:disabled="mode == 'view'" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="备注" prop="remark">
							<el-input v-model="formData.remark" placeholder="请填写备注" :disabled="mode == 'view'" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col>
						<el-form-item label="附件" prop="attachList">
							<el-image class="filesClass" :src="item" :zoom-rate="1" :max-scale="7" :min-scale="0.2"
								:preview-src-list="attachList" :initial-index="index" fit="cover" v-if="mode == 'view'"
								v-for="(item,index) in attachList" :key="index" />
							<upload businessType="PORD_WORK_FINISH_WORK" businessId="" :fileList1="attachList"
								@changeFile="changeFile" fileTypeName=".jpeg, .png, .jpg" v-else />
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
		</div>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="closeDialog">取消</el-button>
				<el-button type="primary" @click="confirm">
					确认
				</el-button>
			</div>
		</template>
	</el-dialog>
</template>

<script setup>
	import {
		ref,
		onMounted,
		reactive,
		defineEmits,
		defineExpose,
		nextTick
	} from "vue";
	import {
		ElMessage,
		ElMessageBox,
		ElNotification
	} from "element-plus";
	import Select from '@/components/Select/index.vue'
	import RemoteSelect from '@/components/RemoteSelect/index.vue';
	import tugApi from '@/api/basicData/tug';
	import recordApi from '@/api/plan/plan/recordIndex'
	import api from '@/api/plan/plan/index';
	import workItemApi from '@/api/basicData/workItem';
	import upload from '@/components/upload.vue';
	import publicApi from '@/api/public'
	const emit = defineEmits(['callback'])
	const selects = ref({
		tugList: [],
		workItemList: []
	})

	const visible = ref(false)
	const mode = ref('add')
	const row = ref({})
	const attachList = ref([])
	const formData = ref({
			tugId: '',
			tugNo: '',
			beginTime: '',
			endTime: '',
			workItemId: '',
			workItemName: '',
			customerId:'',
			customerName:'',
			portAreaCode:'04',
			portAreaName:'',
			workLocation:'',
			remark:'',
			status:0,
			oilConsume:'',
			distance:'',
			attachList:[]
		})
	const ruleForm = ref({})
	const validateAmount = (rule, value, callback) => {
		if (!value) {
			return callback()
		}
		// 使用正则表达式校验小数点后是否只有两位  
		if (!/^-?\d+(\.\d{1,2})?$/.test(value)) {
			callback(new Error('请输入数字'));
		} else {
			// 注意：这里可能还需要进一步处理，确保末尾不是".00"之类的，但为简化示例，暂不处理  
			callback();
		}
	}
	const rules = ref({
		tugId: [{
			required: true,
			message: '不能为空',
			trigger: 'blur'
		}],
		workItemId: [{
			required: true,
			message: '不能为空',
			trigger: 'blur'
		}],
		beginTime: [{
			required: true,
			message: '不能为空',
			trigger: 'blur'
		}],
		endTime: [{
			required: true,
			message: '不能为空',
			trigger: 'blur'
		}],
		customerId: [{
			required: true,
			message: '不能为空',
			trigger: 'blur'
		}],
		portAreaCode: [{
			required: true,
			message: '不能为空',
			trigger: 'blur'
		}],
		workLocation: [{
			required: true,
			message: '不能为空',
			trigger: 'blur'
		}],
		/* attachList: [{
			required: true,
			message: '不能为空',
			trigger: 'blur'
		}], */
		oilConsume: [{
			validator: validateAmount,
			trigger: 'blur'
		}],
		distance: [{
			validator: validateAmount,
			trigger: 'blur'
		}],
	})
	// 文件上传
	const changeFile = file => {
		console.log(file);
		formData.value.attachList = file
	}
	// 展示
	const show = params => {
		visible.value = true
		mode.value = params?.mode || 'add'
		attachList.value = []
		if (mode.value === 'edit' || mode.value === 'view') {
			row.value = params.row;
			editInit();
		}else{
			formData.value = {
					tugId: '',
					tugNo: '',
					beginTime: '',
					endTime: '',
					workItemId: '',
					workItemName: '',
					customerId:'',
					customerName:'',
					portAreaCode:'04',
					portAreaName:'',
					workLocation:'',
					remark:'',
					status:0,
					oilConsume:'',
					distance:'',
					attachList:[]
				}
		}
		getSelectList()
	}
	// 编辑
	const editInit = async () => {
		var files = []
		recordApi.getDetailById({
			id: row.value.id
		}).then(res => {
			//判断是否存在文件
			if (res.data.attachList.length > 0) {
				res.data.attachList.forEach(item => {
					files.push({
						id: item.fileId,
						fileSuffix: item.url.substring(item.url.lastIndexOf('.'), item.url
							.length),
						fileName: item.url.substring(item.url.lastIndexOf('/') + 1, item
							.url
							.length)
					})
				})
			}
			formData.value = res.data;
			formData.value.customerId += ''
		}).then(_ => {
			formData.value.attachList = files.map(v => v.id)
			attachList.value = files;
		}).then(_ => {
			if (mode.value == 'view') {
				attachList.value = []
				formData.value.attachList.forEach(item => {
					publicApi.down(item, 'arraybuffer').then(res => {
						const blob = new Blob([res.data], {
							type: 'application/png;charset=utf-8'
						})
						attachList.value.push(window.URL.createObjectURL(blob))
					})
				})
			}
		})
	}
	// 确认
	const confirm = () => {
		ruleForm.value.validate(valid => {
			if (valid) {
				if (mode.value === 'add') {
					delete formData.value.id;
				}
				recordApi.save(formData.value).then(res => {
					if (res.code == '200') {
						ElMessage.success('保存成功')
						visible.value = false;
						emit("callback");
					} else {
						ElMessage.error(res.msg)
					}
				})
			} else {
				ElMessage.warning('请完善表单信息！')
			}
		})
	}

	// 重置
	const closeDialog = () => {
		nextTick(() => {
			visible.value = false
			ruleForm.value.resetFields()
		})
	}
	defineExpose({
		show
	})
	const getSelectList = () => {
		selects.value.tugList = []
		selects.value.workItemList = []
		tugApi.getList({
			startPage: 1,
			pageSize: 100
		}).then(res => {
			if (res.data.records.length > 0) {
				res.data.records.forEach(item => {
					selects.value.tugList.push({
						label: item.tugNo,
						value: item.id,
						portAreaCode:'04'
					})
				})
			}
		})
		workItemApi.getList({
			startPage: 1,
			pageSize: 100,
			workTypeCode: 2
		}).then(res => {

			if (res.data.records.length > 0) {
				res.data.records.forEach(item => {
					selects.value.workItemList.push({
						label: item.workItem,
						value: item.id
					})
				})
			}
		})
	}
</script>
<style>
	.filesClass {
		display: inline-block;
		width: 100px;
		height: 100px;
		margin: 0 10px 10px 0;
	}

	.filesClass:nth-child(3n) {
		margin-right: 0;
	}
</style>